﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace Rainbow.common.validation
{
    public class StringRule : ValidationRule
    {
        public string regex { get; set; }

        public string errString { get; set; }

        public int maxLength { get; set; }

        public bool isNullable { get; set; }

        public StringRule()
        {
            maxLength = 0;
            isNullable = true;
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            bool rn = true;

            try
            {
                if (rn && maxLength > 0)
                {
                    if (string.IsNullOrEmpty((string)value))
                    {
                        return new ValidationResult(false, $"不能为空");
                    }

                    if (((string)value).Length > maxLength)
                    {
                        string errMsg = String.Format("已经超过最大长度[{0}]", maxLength);
                        return new ValidationResult(false, errMsg);
                    }

                }

                if (!string.IsNullOrEmpty(regex))
                {
                    rn = Regex.IsMatch((string)value, regex);
                }

                if (!isNullable)
                {
                    if (string.IsNullOrEmpty((string)value))
                    {
                        return new ValidationResult(false, $"不能为空");
                    }
                }

            }
            catch (Exception e)
            {
                return new ValidationResult(false, $"输入字符不合法或者{e.Message}");
            }

            if (rn == false)
            {
                return new ValidationResult(false, errString);
            }

            return ValidationResult.ValidResult;
        }
    }
}
